package com.yyfax.ph.home.recommendloan.basicinfo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.common.cache.CacheManager;
import com.yyfax.common.form.FormRow;
import com.yyfax.common.form.FormScanView;
import com.yyfax.common.tools.SoftKeyboardUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.PermissionFragment;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.location.LocationPresenter;
import com.yyfax.ph.common.scan.idcard.activity.IdCardInfo;
import com.yyfax.ph.common.scan.idcard.activity.ScanIdCardActivity;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.common.widgets.pickerview.view.OptionsPickerView;
import com.yyfax.ph.home.imageupload.UploadImagePresenter;
import com.yyfax.ph.home.recommendloan.PageDownEvent;
import com.yyfax.ph.home.recommendloan.RecommendLoanActivity;
import com.yyfax.ph.home.recommendloan.creditinfo.UploadCreditPaperFragment;
import com.yyfax.ph.personal.about.branch.BranchModel;
import com.yyfax.ph.personal.about.branch.BranchPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * 基本资料
 * Created by ying_he on 2017/11/6.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class BasicInfoFragment extends PermissionFragment implements CheckInBasicInfoPresenter.View, LocationPresenter.View,
		BranchPresenter.View, UploadImagePresenter.View, FormScanView.onScanClickListener, TextWatcher {

	private static final int LOADER_ID_CHECK_IN_BASIC_INFO = 1005;
	private static final int LOADER_ID_CHECK_IN_LOCATION = 1006;
	private static final int LOADER_ID_CHECK_IN_BRANCH = 1009;
	private static final int LOADER_ID_UPLOAD_IMAGE = 10010;

	private static final String SELECT_BRANCH = "select_branch";
	private static final String ID_CARD_INFO = "id_card_info";
	private static final String USER_CERT_ID = "user_cert_id";
	private static final String USER_NAME = "user_name";
	private static final String USER_PHONE = "user_phone";
	private static final String CUSTOMER_MANAGER = "customer_manager";
	private static final String SAVED_RECOMMEND_ID = "recommend_id";
	private static final String HAS_CREDIT_PAPER = "has_credit_paper";
	private static final String HAS_DO_LOCATION = "has_do_location";

	@BindView(R.id.location_layout)
	FormRow mLocationLayout;
	@BindView(R.id.id_card_layout)
	FormRow mIdCardLayout;
	@BindView(R.id.name_layout)
	FormRow mNameLayout;
	@BindView(R.id.phone_layout)
	FormRow mPhoneLayout;
	@BindView(R.id.credit_switch)
	Switch mCreditSwitch;
	@BindView(R.id.customer_manager_layout)
	FormRow mCustomerManagerLayout;
	@BindView(R.id.next_step_tv)
	Button mNextStepTv;

	Unbinder mUnBinder;
	private CheckInBasicInfoPresenter mCheckPresenter;
	private LocationPresenter mLocationPresenter;
	private BranchPresenter mBranchPresenter;
	private UploadImagePresenter mUploadImagePresenter;
	private BranchModel.BranchInfo mSelectedBranchInfo;
	private OptionsPickerView<BranchModel.BranchInfo> mBranchPicker;
	private ArrayList<BranchModel.BranchInfo> mBranchInfoList = new ArrayList<>();

	private String mLocatedCity = "";
	private boolean mHasDoLocation = false; // 是否发起过定位请求,并返回,不管成功或失败.

	private IdCardInfo mIdCardInfo;
	private CheckInBasicInfoModel.BasicInfo mBasicInfo;
	// 如果是重建, 则根据保存数据判断是否需要进行自动定位
	private boolean mNeedRequestLocationBackground = false;
	private int mPermissionRequestCodeCamera = DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE;
	private int mPermissionRequestCodeLocation = DEFAULT_PERMISSION_REQUEST_CODE_LOCATION;
	private boolean mIsManualLocation = false; // 是否是手动点击发起定位请求
	private String mIdCardImageId = "";

	public static Fragment newInstance() {
		return new BasicInfoFragment();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		getLoaderManager().initLoader(LOADER_ID_CHECK_IN_BASIC_INFO, null, this);
		getLoaderManager().initLoader(LOADER_ID_CHECK_IN_LOCATION, null, this);
		getLoaderManager().initLoader(LOADER_ID_CHECK_IN_BRANCH, null, this);
		getLoaderManager().initLoader(LOADER_ID_UPLOAD_IMAGE, null, this);
	}

	@Override
	public void onDetach() {
		super.onDetach();
		getLoaderManager().destroyLoader(LOADER_ID_CHECK_IN_BASIC_INFO);
		getLoaderManager().destroyLoader(LOADER_ID_CHECK_IN_LOCATION);
		getLoaderManager().destroyLoader(LOADER_ID_CHECK_IN_BRANCH);
		getLoaderManager().destroyLoader(LOADER_ID_UPLOAD_IMAGE);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.check_in_basic_info_fragment_layout, null);
		mUnBinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initView(savedInstanceState);
	}

	private void initView(Bundle bundle){
		((FormScanView) mIdCardLayout.getRightView()).setOnScanClickListener(this);
		((FormScanView) mIdCardLayout.getRightView()).addTextChangedListener(this);

		if (bundle != null) {
			String name = bundle.getString(USER_NAME, "");
			mIdCardInfo = bundle.getParcelable(ID_CARD_INFO);
			String idCardNum = bundle.getString(USER_CERT_ID, "");
			String phone = bundle.getString(USER_PHONE, "");
			String customerManager = bundle.getString(CUSTOMER_MANAGER, "");
			mSelectedBranchInfo = bundle.getParcelable(SELECT_BRANCH);
			boolean hasCreditPapers = bundle.getBoolean(HAS_CREDIT_PAPER);
			mHasDoLocation = bundle.getBoolean(HAS_DO_LOCATION, false);

			if (mSelectedBranchInfo != null) {
				mLocationLayout.setText(mSelectedBranchInfo.city);
			}else {
				mNeedRequestLocationBackground = true;
			}
			mNameLayout.setText(name);
			mIdCardLayout.setText(idCardNum);
			mPhoneLayout.setText(phone);
			if (!TextUtils.isEmpty(customerManager)) {
				mCustomerManagerLayout.setText(customerManager);
			}
			mCreditSwitch.setChecked(hasCreditPapers);
		}else {
			mNeedRequestLocationBackground = true;
		}

		// 如果恢复字段里客户经理字段为空,则判断本地缓存里是否有客户经理字段.
		if (TextUtils.isEmpty(mCustomerManagerLayout.getText())){
			String customerManager = CacheManager.readObject(Constants.CUSTOMER_MANAGER);
			if (customerManager != null) {
				mCustomerManagerLayout.setText(customerManager);
			}
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_CHECK_IN_BASIC_INFO:
				return new PresenterLoader<>(getActivity(), new CheckInBasicInfoPresenter.Generator());
			case LOADER_ID_CHECK_IN_LOCATION:
				return new PresenterLoader<>(getActivity(), new LocationPresenter.Generator());
			case LOADER_ID_CHECK_IN_BRANCH:
				return new PresenterLoader<>(getActivity(), new BranchPresenter.Generator());
			case LOADER_ID_UPLOAD_IMAGE:
				return new PresenterLoader<>(getActivity(), new UploadImagePresenter.Generator());
			default:
				return null;
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_CHECK_IN_BASIC_INFO:
				mCheckPresenter = (CheckInBasicInfoPresenter) data;
				mCheckPresenter.attach(this);
				break;
			case LOADER_ID_CHECK_IN_LOCATION:
				mLocationPresenter = (LocationPresenter) data;
				mLocationPresenter.attach(this);
				// 如果不是恢复数据, 则需要后台发起定位请求.
				if (mNeedRequestLocationBackground){
					mLocationPresenter.createModel(getActivity());
					getLocation(false);
				}
				break;
			case LOADER_ID_CHECK_IN_BRANCH:
				mBranchPresenter = (BranchPresenter) data;
				mBranchPresenter.attach(this);
				break;
			case LOADER_ID_UPLOAD_IMAGE:
				mUploadImagePresenter = (UploadImagePresenter) data;
				mUploadImagePresenter.attach(this);
				break;
				default:
					break;
		}
	}

	@OnClick({R.id.location_layout, R.id.next_step_tv})
	public void onClicked(View view) {
		switch (view.getId()) {
			case R.id.location_layout:
				SoftKeyboardUtils.hideKeyboard(getActivity());
				chooseLocation();
				break;
			case R.id.next_step_tv:
				checkAdmittance();
				break;
				default:
					break;
		}
	}

	private void chooseLocation() {
		if (mBranchPicker != null && mHasDoLocation) {
			mBranchPicker.show();
		} else if (mBranchPicker == null && mHasDoLocation){
			mBranchPresenter.getBranchInfo(true);
		} else {
			getLocation(true);
		}
	}

	private void getLocation(boolean isManual) {
		mIsManualLocation = isManual;
		if (getLocationPermission(mPermissionRequestCodeLocation)) {
			if (mLocationPresenter != null) {
				mHasDoLocation = true;
				mLocationPresenter.getLocation(getActivity(), isManual);
			}
		}
	}

	/**
	 * 跳转身份证扫描
	 */
	private void goToScanIdCard() {
		if (hasCameraPermission(mPermissionRequestCodeCamera)) {
			Intent intent = new Intent(getActivity(), ScanIdCardActivity.class);
			intent.putExtra(ScanIdCardActivity.BOTH_DIRECTION, true);
			ScanIdCardActivity.startForResult(getActivity(), intent, RecommendLoanActivity.MSG_GET_SCAN_ID_CARD);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
				case RecommendLoanActivity.MSG_GET_SCAN_ID_CARD://扫描身份证
					if (data.hasExtra(ScanIdCardActivity.IDINFO)) {
						mIdCardInfo = data.getParcelableExtra(ScanIdCardActivity.IDINFO);
						if (mIdCardInfo != null) {
							//mActivity.setIdCardInfo(mIdCardInfo);
							String result = mIdCardInfo.getIdNumber();
							String name = mIdCardInfo.getName();
							mIdCardLayout.setText(result);
							mIdCardLayout.validate();//扫描身份证后, 检查年龄时候符合要求
							mNameLayout.setText(name);
							if (!TextUtils.isEmpty(result)) {
								((FormScanView) mIdCardLayout.getRightView()).setCanEdit(false);
							}
							if (!TextUtils.isEmpty(mIdCardInfo.getIdFrontHeaderImgPath())) {
								mUploadImagePresenter.uploadImage(mIdCardInfo.getIdFrontHeaderImgPath(), Constants.IMAGE_TYPE_ID_CARD_HEAD);
							}
						}
					}
					break;
				default:
					break;
			}
		}
	}

	public void checkAdmittance() {
		if (!mLocationLayout.validate() || !mIdCardLayout.validate() || !mNameLayout.validate() || !mPhoneLayout.validate()) {
			return;
		}
		if (!mCreditSwitch.isChecked() && TextUtils.isEmpty(mCustomerManagerLayout.getText())){
			showToast(R.string.customer_manager_input_hint);
			return;
		}

		showLoading(false);
		setBasicInfo();
		mCheckPresenter.checkAdmittance(mBasicInfo.certId, mBasicInfo.name);
	}

	private void setBasicInfo(){
		if (mBasicInfo == null){
			mBasicInfo = new CheckInBasicInfoModel.BasicInfo();
		}

		mBasicInfo.name = mNameLayout.getText();
		mBasicInfo.certId = mIdCardLayout.getText();
		mBasicInfo.phone = mPhoneLayout.getText();
		mBasicInfo.outletId = mSelectedBranchInfo.id; // 常住城市
		// 是否有纸质报告
		if (mCreditSwitch.isChecked()){
			mBasicInfo.type = CheckInBasicInfoPresenter.HAS_CREDIT_PAPERS;
		}else {
			mBasicInfo.type = CheckInBasicInfoPresenter.NO_CREDIT_PAPERS;
		}
		mBasicInfo.customerMgr = mCustomerManagerLayout.getText();
		if (mIdCardInfo != null) {
			mBasicInfo.ethnicity = mIdCardInfo.getNationality();
			mBasicInfo.address = mIdCardInfo.getAddress();
			mBasicInfo.authority = mIdCardInfo.getAuthority();
			mBasicInfo.validity = mIdCardInfo.getValidity();
			mBasicInfo.sex = mIdCardInfo.getSex();
		}
		mBasicInfo.certPhoto = mIdCardImageId;
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeCamera){
			goToScanIdCard();
		}else if (requestCode == mPermissionRequestCodeLocation){
			getLocation(mIsManualLocation);
			mIsManualLocation = false;
		}
	}

	@Override
	public void permissionsAllGrantedFailure(int requestCode) {
		super.permissionsAllGrantedFailure(requestCode);
		if (requestCode == mPermissionRequestCodeLocation){
			if (mBranchPicker == null) {
				if (mBranchPresenter != null) {
					mBranchPresenter.getBranchInfo(mIsManualLocation);
					mIsManualLocation = false;
				}
			} else {
				if (mIsManualLocation) {
					mBranchPicker.show();
				}
			}
		}
	}

	@Override
	public void onGetCitySuccess(String city, boolean isManual) {
		mLocatedCity = city;
		if (mBranchPicker == null) {
			if (mBranchPresenter != null) {
				mBranchPresenter.getBranchInfo(isManual);
			}
		} else {
			if (isManual) {
				mBranchPicker.show();
			}
		}
	}

	@Override
	public void onGetCityFailure(boolean isManual) {
		dismissLoading();
		showToast(R.string.get_location_failure);
		if (mBranchPicker == null) {
			if (mBranchPresenter != null) {
				mBranchPresenter.getBranchInfo(isManual);
			}
		} else {
			if (isManual) {
				mBranchPicker.show();
			}
		}
	}

	@Override
	public void getBranchSuccess(List<BranchModel.BranchInfo> branchList, boolean isManual) {
		if (null != branchList && branchList.size() > 0) {
			branchList = mBranchPresenter.filter(branchList);
			if (mBranchInfoList.size() > 0) {
				mBranchInfoList.clear();
			}

			mBranchInfoList.addAll(branchList);
			mBranchPicker = new OptionsPickerView<>(getActivity());
			mBranchPicker.setPicker(mBranchInfoList);
			mBranchPicker.setCyclic(false, false, false);
			mBranchPicker.setSelectOptions(0, 0, 0);
			mBranchPicker.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
				@Override
				public void onOptionsSelect(int options1, int option2, int options3) {
					mSelectedBranchInfo = mBranchInfoList.get(options1);
					String tx = mSelectedBranchInfo.getPickerViewText();
					mLocationLayout.setText(tx);
				}
			});


			// 如果是手动点击地址, 则弹出地址选择框; 否则直接将定位得到的地址显示在地址里.
			if (isManual) {
				mBranchPicker.show();
			} else {
				if (null != mBranchInfoList && mBranchInfoList.size() > 0) {
					for (BranchModel.BranchInfo branchInfo : mBranchInfoList) {
						if (mLocatedCity.contains(branchInfo.city)) {
							mLocationLayout.setText(branchInfo.city);
							mSelectedBranchInfo = branchInfo;
						}
					}
				}
			}
		}
	}

	@Override
	public void getShareSuccess(BranchModel.Share share) {

	}

	@Override
	public void getBranchFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void getShareFailure(String tips) {

	}

	@Override
	public void checkInBasicInfo(CheckInBasicInfoModel.CheckBasicInfoBean checkBasicInfoBean) {
		dismissLoading();
		mBasicInfo.rcmdId = checkBasicInfoBean.rcmdId;
		 // 如果选择无征信报告,则需要把扫描身份证得到的正反面照片传到下一个页面.
		UploadCreditPaperFragment.ExtraParamsToUploadCredit extraParamsToUploadCredit = new UploadCreditPaperFragment.ExtraParamsToUploadCredit();
		if (mIdCardInfo != null) {
			extraParamsToUploadCredit.idFrontImgPath = mIdCardInfo.getIdFrontImgPath();
			extraParamsToUploadCredit.idBackImgPath = mIdCardInfo.getIdBackImgPath();
		}
		extraParamsToUploadCredit.rcmId = mBasicInfo.rcmdId;
		if (mCreditSwitch.isChecked()) {
			extraParamsToUploadCredit.bizType = UploadCreditPaperFragment.BIZ_TYPE_HAS_CREDIT_RECOMMEND_UPLOAD;
		}else {
			extraParamsToUploadCredit.bizType = UploadCreditPaperFragment.BIZ_TYPE_NO_CREDIT_RECOMMEND_UPLOAD;
		}
		EventAgent.post(new PageDownEvent(RecommendLoanActivity.PAGE_UPLOAD_CREDIT, extraParamsToUploadCredit));
	}

	@Override
	public void checkInBasicInfoFailure(String tips) {
		dismissLoading();
		showTipsDialog(tips);
	}

	@Override
	public void checkAdmittanceOk() {
		// 准入成功后,保存客户经理到本地, 下次进入自动填充.
		String customerManagerStr = mCustomerManagerLayout.getText();
		if (!TextUtils.isEmpty(customerManagerStr)) {
			CacheManager.writeObject(customerManagerStr, Constants.CUSTOMER_MANAGER);
		}

		setBasicInfo();
		mCheckPresenter.checkInBasicInfo(mBasicInfo);
	}

	@Override
	public void checkAdmittanceAlert(String tips) {
		dismissLoading();
		showTipsDialog(tips);
	}

	@Override
	public void checkAdmittanceConfirm(String tips) {
		dismissLoading();
		showTipsDialog(tips);
	}

	@Override
	public void checkAdmittanceError(String tips) {
		dismissLoading();
		showTipsDialog(tips);
	}

	@Override
	public void onScanClick(View view) {
		StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_B002);
		goToScanIdCard();
	}

	@Override
	public void onUploadImage(String filePath, String fileName, String imageId) {
		mIdCardImageId = imageId;
	}

	@Override
	public void onUploadImageFailure(String filePath, String tips) {

	}

	@Override
	public void onUploadImageCancel(String filePath, String tips) {

	}

	/**
	 * 按了回退按钮
	 */
	public void onBackPressed() {
		if (!needShowWarningAlert()) {
			if (null != getActivity()) {
				getActivity().finish();
			}
		} else {
			showTipsDialog(getString(R.string.exit_recommend_strs), R.string.give_up, R.string.continue_recommend, new DialogBase.BottomTwoClickListener() {
				@Override
				public void onCancelClick(DialogBase dialog) {
					getActivity().finish();
				}

				@Override
				public void onConfirmClick(DialogBase dialog) {
					dialog.dismiss();
				}
			}, false);
		}
	}

	/**
	 * 是否需要弹出回退警示
	 * @return
	 */
	public boolean needShowWarningAlert() {
		if (null != mLocationLayout && null != mCustomerManagerLayout && null != mNameLayout
				&& null != mIdCardLayout && null != mPhoneLayout ) {
			String name = mNameLayout.getText();
			String idCardNum = mIdCardLayout.getText();
			String phone = mPhoneLayout.getText();

			if (!TextUtils.isEmpty(name) || !TextUtils.isEmpty(idCardNum) || !TextUtils.isEmpty(phone)){
				return true;
			}
		}
		return false;
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		//如果扫描之后又修改了身份证号，则清空身份证的一些信息
		String idCardStr = mIdCardLayout.getText();
		if (!TextUtils.isEmpty(idCardStr) && idCardStr.length() == 18) {
			if (null != mIdCardInfo && !TextUtils.isEmpty(mIdCardInfo.getIdNumber())) {
				if (!idCardStr.equalsIgnoreCase(mIdCardInfo.getIdNumber())) {
					mIdCardInfo = null;
				}
			}
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		String name = mNameLayout.getText();
		String idCardNum = mIdCardLayout.getText();
		String phone = mPhoneLayout.getText();
		String customerManager = mCustomerManagerLayout.getText();
		outState.putString(USER_NAME, name);
		outState.putString(USER_CERT_ID, idCardNum);
		outState.putString(USER_PHONE, phone);
		outState.putString(CUSTOMER_MANAGER, customerManager);
		if (mIdCardInfo != null) {
			outState.putParcelable(ID_CARD_INFO, mIdCardInfo);
		}
		if (mBasicInfo != null) {
			outState.putString(SAVED_RECOMMEND_ID, mBasicInfo.rcmdId);
		}
		if (mSelectedBranchInfo != null) {
			outState.putParcelable(SELECT_BRANCH, mSelectedBranchInfo);
		}
		outState.putBoolean(HAS_CREDIT_PAPER, mCreditSwitch.isChecked());
		outState.putBoolean(HAS_DO_LOCATION, mHasDoLocation);
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnBinder.unbind();
	}
}
